package jp.co.baka.pachinko.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jp.co.baka.pachinko.dto.UserDto;
import jp.co.baka.pachinko.meta.UserMstMeta;
import jp.co.baka.pachinko.model.UserMst;
import jp.co.baka.pachinko.util.RequestUtil;

import org.slim3.datastore.Datastore;
import org.slim3.util.RequestLocator;
import org.slim3.util.StringUtil;

public class UserService {

    //ユーザセッション　アトリビュート名
    private static final String USER_SESSION_ATTR_NAME="USER_SESSION_ATTR_NAME";


    /**
     * セッションからユーザを取得する
     *
     * セッションが切れた場合はuuidクッキーから再セットする
     *
     * セッション、uuidクッキーが無効な場合はNULLを返す
     *
     * @return
     */
    public static UserDto getUser(){

        UserDto user = null;


        HttpServletRequest req = RequestLocator.get();
        HttpSession sesseion = req.getSession(true);

        if(sesseion.isNew()){
            //セッションが切れて再生成された場合
            String uuid = RequestUtil.getCookeiValue(req,"uuid");
            user = searchUserByUUID(uuid);
            if(user!=null){
                sesseion.setAttribute(USER_SESSION_ATTR_NAME, user);
            }
        }else{

            Object so = sesseion.getAttribute(USER_SESSION_ATTR_NAME);

            if(so==null){
                String uuid = RequestUtil.getCookeiValue(req,"uuid");
                user = searchUserByUUID(uuid);
                if(user!=null){
                    sesseion.setAttribute(USER_SESSION_ATTR_NAME, user);
                }
            }else{
                user = (UserDto)so;
            }

        }

        return user;
    }


    /**
     *
     * UUIDクッキーを発行し、セッションにユーザを追加する
     *
     *
     * @param user
     * @param req
     * @param res
     */
    public static void addSessionAndCookie(UserMst user,HttpServletRequest req,HttpServletResponse res){


        String uuid = null;
        try {
            uuid = URLEncoder.encode(user.getUuid(),"UTF-8");
        } catch (UnsupportedEncodingException e) {

        }
        Cookie cuuid = new Cookie("uuid",uuid);
        cuuid.setPath("/");

        //クッキーの有効期間 50年（笑
        int keetTime = 60*60*24*365*50;

        cuuid.setMaxAge(keetTime);

        res.addCookie(cuuid);


        UserDto sessionUser = new UserDto();
        sessionUser.setUserId(user.getUserId());
        sessionUser.setUuid(user.getUuid());
        sessionUser.setUserName(user.getUserName());

        req.getSession().setAttribute(USER_SESSION_ATTR_NAME, sessionUser);


    }

    public static UserDto searchUserByUUID(String uuid){

        UserDto user = null;

        if(!StringUtil.isEmpty(uuid)){

            UserMstMeta u = UserMstMeta.get();
            UserMst userMst = Datastore.query(u).filter(u.uuid.equal(uuid)).asSingle();
            if(userMst!=null){
                user = new UserDto();
                user.setUserId(userMst.getUserId());
                user.setUserName(userMst.getUserName());
                user.setUuid(userMst.getUuid());
            }
        }

        return user;
    }


}
